<?php
namespace App\Library;

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Upload {
    private static $accessKey = null;
    private static $secretKey = null;

    public function __construct() {
        self::$accessKey = env('accessKey');
        self::$secretKey = env('secretKey');
    }

    public function img($file) {
        $type = ['image/jpeg', 'image/gif', 'image/jpeg'];
        if(!in_array($file->getMimeType(), $type)) {
            return ['status' => false, 'data' => '文件类型不允许'];
        }
        $path = 'img';
        if(!file_exists($path)) {
            mkdir($path);
        }
        $fileName = $file->getClientOriginalName();
        $file->move($path, $fileName);
        $info = substr(strrchr($fileName, '.'), 1);

        $auth  = new Auth(self::$accessKey, self::$secretKey);
        $token = $auth->uploadToken('woddp');
        // 要上传文件的本地路径
        $filePath = $path . '/' . $fileName;
        // 上传到七牛后保存的文件名
        $key = time() . '.' . $info;

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if(!empty($ret) && isset($ret['key'])) {
            unlink($filePath); //上传到七牛云后删除本地图片
            return ['status' => true, 'data' => env('qiniu_url') . $ret['key']];

        } else {
            return ['status' => false, 'data' => '上传失败', 'error' => $err];
        }
    }

    public function getFile($fileName) {

        //初始化Auth状态
        $auth = new Auth(self::$accessKey, self::$secretKey);

        //初始化BucketManager
        $bucketMgr = new BucketManager($auth);

        //你要测试的空间， 并且这个key在你空间中存在
        $bucket = 'woddp';
        $key    = $fileName;

        //获取文件的状态信息
        list($ret, $err) = $bucketMgr->stat($bucket, $key);
        if($err !== null) {
            return $err;
        } else {
            return $ret;
        }
    }
}